﻿#pragma once
#include <iostream>
#include "UtilToml.h"
#include <fstream>
#include <filesystem>


//filePath
UtilToml::UtilToml() {
	//初始化
	initToml();

}
UtilToml::~UtilToml() {

}
void UtilToml::importToml(std::string fileName) {
	//导入，读取toml文件，然后写入到AppConfig::configPath
	try {
		toml::value data = toml::parse(fileName);
		writeTomlFile(data);
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
	}
}
void UtilToml::exportToml(std::string fileName) {
	//导出
	toml::value data;
	readTomlFile(data);
	std::ofstream ofs(fileName);
	if (!ofs.is_open()) {
		std::cerr << "Error: Could not open file for writing: " << fileName << std::endl;
		return;
	}
	ofs << data;
	ofs.close();
}
void UtilToml::initToml() {
	if (!std::filesystem::exists(AppConfig.configPath)) {
		this->createTomlFile();
	}
}
//filePath
void UtilToml::readTomlFile(toml::value& data) {
	try {
		// 使用toml11库读取TOML文件,并将其解析为toml::value类型的数据
		data = toml::parse(AppConfig.configPath);

		// find a value with the specified type from a table
	}
	catch (const std::exception& err) {
		std::cerr << "Error while parsing TOML file: " << err.what() << std::endl;
	}
}

void UtilToml::writeTomlFile(toml::value& data) {
	try {
		std::ofstream file(AppConfig.configPath);
		if (!file.is_open()) {
			std::cerr << "Error: Could not open file for writing: " << AppConfig.configPath << std::endl;
			return;
		}
		file << data;
		file.close();
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
	}
}
//创建文件
void UtilToml::createTomlFile() {
	//判断文件是否存在
	try {
		// 将数据写入文件
		// 创建一个输出流对象指向要写的文件
		std::ofstream ofs(AppConfig.configPath, std::ios::out | std::ios::trunc);
		if (!ofs.is_open()) {
			std::cerr << "Error: Could not open file for writing." << std::endl;
			return;
		}
		// 将toml::table序列化并写入文件
		std::vector<std::string> a{ "VALORANT-Win64-Shipping.exe" };
		const toml::value v{
			{"processNames",a},
			{"hideKey", "T"},  
			{"showKey", "Y"}, 
		};

		try {
			ofs << v;
		}
		catch (const std::exception& e) {
			std::cerr << "Failed to write to file: " << e.what() << std::endl;
		}

		// 关闭输出流
		ofs.close();
	
	}
	catch (const std::exception& e) {
		std::cerr << "Error: " << e.what() << std::endl;
	}
}
